﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace BLL
{
    /// <summary>
    /// 加密辅助类
    /// </summary>
    public class EncryptHelper
    {
        /// <summary>
        /// 生成加密密钥
        /// </summary>
        public static string GenerateSalt()
        {
            byte[] data = new byte[0x10];
            new RNGCryptoServiceProvider().GetBytes(data);
            return Convert.ToBase64String(data);
        }

        /// <summary>
        /// 加密密码
        /// </summary>
        /// <param name="pass">原密码</param>
        /// <param name="passwordFormat">加密方法，0为不加密，1为SHA1加密</param>
        /// <param name="salt">密钥</param>
        /// <returns>加密后字符串</returns>
        public static string GomputeSHA1Value(string pass, string salt)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
            byte[] src = Convert.FromBase64String(salt);
            byte[] dst = new byte[src.Length + bytes.Length];
            byte[] inArray = null;
            Buffer.BlockCopy(src, 0, dst, 0, src.Length);
            Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);

            /*
             * HashAlgorithm Simple Name：SHA，SHA1，MD5，SHA256，SHA-256，SHA384，SHA-384，SHA512，SHA-512
             */
            HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
            inArray = algorithm.ComputeHash(dst);
            return Convert.ToBase64String(inArray);
        }

        /// <summary>
        /// MD5加密算法
        /// </summary>
        /// <param name="strSource">需要加密的明文</param>
        /// <returns>返回32位加密结果</returns>
        public static string ComputeMD5Value(string strSource)
        {
            string strResult = "";

            //Create
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();

            //注意编码UTF8、UTF7、Unicode等的选择　
            byte[] bytResult = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));

            //字节类型的数组转换为字符串
            for (int i = 0; i < bytResult.Length; i++)
            {
                //16进制转换 
                strResult = strResult + bytResult[i].ToString("X");
            }
            return strResult;
        }
    }
}
